from fastapi import APIRouter,Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from database import get_db
from schemas.patient_schemas import PatientCreate, PatientUpdate
from services.auth_service import require_user


from config import * #导入所有配置
from models.user_models import *

from services.user_service import get_all_users,get_user,create_user,delete_user,update_user

router = APIRouter()

# 查询获取所有的病人的信息
@router.get("/patients")
def get_all_patients(db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PATIENT))):
    return get_all_users(UserType.PATIENT,db)

# 查询单个病人的信息
@router.get("/patients/{patient_id}")
def get_patient(patient_id:int,db: Session = Depends(get_db),user=Depends(require_user(UserType.ADMIN, UserType.PATIENT))):
    return get_user(UserType.PATIENT,db,patient_id)

@router.post("/patients")
def create_patient(patient: PatientCreate, db: Session = Depends(get_db),
                    user=Depends(require_user(UserType.ADMIN))):
    return create_user(UserType.PATIENT,db,patient)


@router.delete("/patients/{patient_id}")
def delete_patient(patient_id: int,db: Session = Depends(get_db),
                   user=Depends(require_user(UserType.ADMIN))):
    return delete_user(UserType.PATIENT,db,patient_id)


@router.put("/patients/{patient_id}")
def update_patient(patient_id: int, patient_update: PatientUpdate, db: Session = Depends(get_db),
                   user=Depends(require_user(UserType.ADMIN,UserType.PATIENT))):
    if user["user_type"] == 'PATIENT' and user['user_ref_id'] != patient_id:
        raise HTTPException(
            status_code=403,
            detail="Permission denied: patients can only update their own information."
        )
    return update_user(UserType.PATIENT,db,patient_update,patient_id)
